<template>
  <view class="uni-flex-column container">
    <!-- 搜索框 -->
    <view class="search-bar">
      <uni-search-bar
        v-model="searchText"
        placeholder="输入地址搜索"
        @confirm="handleSearch"
        @clear="clearSearch"
      ></uni-search-bar>
    </view>
    <!-- 地图容器 -->
    <map
      id="map"
      :latitude="center.latitude"
      :longitude="center.longitude"
      :scale="16"
      :markers="markers"
      @regionchange="handleMapDrag"
      class="map-container"
      show-location
    >
      <!-- 固定中心标记 -->
      <cover-view class="fixed-marker">
        <cover-image
          src="/static/location.png"
          style="width: 40px; height: 40px"
        />
      </cover-view>
    </map>
    <view class="info-list">
      <!-- 新增定位按钮 -->
      <view class="location-btn" @click="backToCurrentLocation">
        <image src="/static/location.png" mode="aspectFit"></image>
      </view>
      <!-- 位置信息展示 -->
      <view class="address-card">
        <text class="address">{{ currentAddress }}</text>
        <text class="hint">{{ hintText }}</text>
      </view>

      <!-- 周边POI列表 -->
      <scroll-view scroll-y class="poi-list" style="height: 300rpx">
        <view
          v-for="(item, index) in nearbyPOIs"
          :key="index"
          class="poi-item"
          @click="selectPOI(item)"
        >
          <text class="name">{{ item.name }}</text>
          <text class="distance">{{ item.distance }}米</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
// 高德地图可以运行的正确代码
// 配置项
const AMAP_KEY = "6d518c2af578988932d5771864bd1eda";

// 坐标数据
const center = ref({ latitude: 39.90469, longitude: 116.40717 });
const markers = ref([]);
const currentAddress = ref("正在获取位置...");
const hintText = ref("拖动地图查看周边");
const nearbyPOIs = ref([]);
const searchText = ref(''); // 搜索框内容
const searchResults = ref([]); // 搜索结果
// 防抖函数
function debounce(fn, delay) {
  let timer = null;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), delay);
  };
}

// 获取用户位置
const getLocation = async () => {
  try {
    await uni.authorize({
      scope: "scope.userLocation",
      fail: () => {
        uni.showModal({
          title: "提示",
          content: "需要位置权限才能使用地图功能",
          confirmText: "去设置",
          success: (res) => {
            if (res.confirm) uni.openSetting();
          },
        });
        throw new Error("用户拒绝授权");
      },
    });

    const res = await new Promise((resolve, reject) => {
      uni.getLocation({
        type: "gcj02",
        success: resolve,
        fail: reject,
      });
    });

    center.value = {
      latitude: res.latitude,
      longitude: res.longitude,
    };
    return res;
  } catch (err) {
    console.warn("获取位置失败:", err);
    return center.value;
  }
};

// 高德API请求封装
const amapRequest = async (apiPath, params) => {
  try {
    const res = await uni.request({
      url: `https://restapi.amap.com${apiPath}`,
      data: {
        ...params,
        key: AMAP_KEY,
      },
    });

    if (res.data.status !== "1") {
      throw new Error(res.data.info || "高德API请求失败");
    }
    return res.data;
  } catch (e) {
    console.error(`[AMAP] ${apiPath} 请求失败:`, e);
    throw e;
  }
};

// 获取周边POI
const fetchNearbyPOIs = async (latitude, longitude) => {
  try {
    const data = await amapRequest("/v3/place/around", {
      location: `${longitude},${latitude}`,
      radius: 500,
      types: "120000|130000|140000|150000",
      offset: 20,
    });
    nearbyPOIs.value = data.pois.map((item) => ({
      id: item.id,
      name: item.name,
      address: item.address,
      distance: item.distance,
      location: item.location,
    }));
  } catch (e) {
    nearbyPOIs.value = [];
    hintText.value = "加载周边失败，请重试";
  }
};

// 逆地理编码
const reverseGeocode = async (latitude, longitude) => {
  try {
    const data = await amapRequest("/v3/geocode/regeo", {
      location: `${longitude},${latitude}`,
      radius: 50,
    });
    return data.regeocode.formatted_address;
  } catch (e) {
    return "未知位置";
  }
};

// 地图拖动处理（核心修改）
const handleMapDrag = debounce(async (e) => {
  if (e.type === "end") {
    hintText.value = "正在获取新位置...";

    const mapCtx = uni.createMapContext("map");
    mapCtx.getCenterLocation({
      success: async (res) => {
        // 更新中心点坐标
        center.value = {
          latitude: res.latitude,
          longitude: res.longitude,
        };

        // 获取新地址
        currentAddress.value = await reverseGeocode(
          res.latitude,
          res.longitude
        );

        // 重新搜索周边
        await fetchNearbyPOIs(res.latitude, res.longitude);

        hintText.value = "拖动地图可查看其他区域";
      },
      fail: () => {
        hintText.value = "获取中心位置失败";
      },
    });
  }
}, 500);

// 选择POI
const selectPOI = async (item) => {
  const [longitude, latitude] = item.location.split(",");
  const address = await reverseGeocode(latitude, longitude);
  uni.showModal({
    title: item.name,
    content: `${address}\n距离：${item.distance}米`,
    showCancel: false,
  });
};

// 初始化
onMounted(async () => {
  const location = await getLocation();
  currentAddress.value = await reverseGeocode(
    location.latitude,
    location.longitude
  );
  await fetchNearbyPOIs(location.latitude, location.longitude);
});
// 新增方法：返回当前位置
const backToCurrentLocation = async () => {
  hintText.value = "正在定位...";

  try {
    // 重新获取当前位置
    const location = await getLocation();

    // 更新地图中心点
    center.value = {
      latitude: location.latitude,
      longitude: location.longitude,
    };

    // 获取新地址
    currentAddress.value = await reverseGeocode(
      location.latitude,
      location.longitude
    );

    // 重新搜索周边
    await fetchNearbyPOIs(location.latitude, location.longitude);

    hintText.value = "已返回当前位置";
  } catch (err) {
    hintText.value = "定位失败";
    console.error("返回当前位置失败:", err);
  }
};
// 处理搜索
const handleSearch = async () => {
  if (!searchText.value.trim()) return;
  
  uni.showLoading({ title: '搜索中...' });
  try {
    const result = await geocode(searchText.value);
    
    // 更新地图中心
    center.value = {
      latitude: result.latitude,
      longitude: result.longitude
    };
    
    // 更新地址显示
    currentAddress.value = result.address;
    
    // 更新周边POI
    await fetchNearbyPOIs(result.latitude, result.longitude);
    
    // 添加标记点
    markers.value = [{
      id: 999,
      latitude: result.latitude,
      longitude: result.longitude,
      iconPath: '/static/marker.png',
      width: 30,
      height: 30
    }];
    
    hintText.value = '搜索完成';
  } catch (e) {
    uni.showToast({
      title: '搜索失败：' + e.message,
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};
// 地理编码（地址转坐标）
const geocode = async (address) => {
  try {
    const data = await amapRequest('/v3/geocode/geo', {
      address: address,
      city: '' // 可指定城市提高准确性
    });
    
    if (data.geocodes && data.geocodes.length > 0) {
      const [longitude, latitude] = data.geocodes[0].location.split(',');
      return {
        latitude: parseFloat(latitude),
        longitude: parseFloat(longitude),
        address: data.geocodes[0].formatted_address
      };
    }
    throw new Error('未找到匹配地址');
  } catch (e) {
    console.error('地理编码失败:', e);
    throw e;
  }
};
// 清空搜索
const clearSearch = () => {
  searchText.value = '';
  markers.value = [];
};
</script>

<style scoped>
.container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}
.map-container {
   width: 100%;
   height: calc(100% - 46px);
   position: relative;
}
.info-list {
  position: absolute;
  height: 200px;
  bottom: 0;
  left: 20rpx;
  right: 20rpx;
}
/* 新增定位按钮样式 */
.location-btn {
  position: absolute;
  right: 20px;
  bottom: 120px; /* 根据列表高度调整 */
  width: 44px;
  height: 44px;
  background: #fff;
  border-radius: 50%;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.location-btn image {
  width: 24px;
  height: 24px;
}
.fixed-marker {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -100%);
  z-index: 999;
}

.address-card {
  padding: 12px;
  background: #fff;
  border-bottom: 1px solid #eee;
}

.address {
  font-size: 16px;
  font-weight: bold;
  display: block;
}

.hint {
  font-size: 12px;
  color: #888;
  display: block;
  margin-top: 4px;
}

.poi-list {
  flex: 1;
  background: #fff;
}

.poi-item {
  padding: 12px 15px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
}

.name {
  font-size: 15px;
}

.distance {
  color: #07c160;
  font-size: 14px;
}
</style>